import { ChatContext } from '@/app/chat-context';
import { CaretLeftOutlined, CaretRightOutlined, DeleteOutlined, PlusOutlined, MoreOutlined, HistoryOutlined, StarOutlined, UserOutlined, FileExcelOutlined, DownloadOutlined, } from '@ant-design/icons';
import { Flex, Layout, Button, Menu, List, Popover, Progress, Tooltip, message,Image } from 'antd';
import React, { useContext, useMemo, useState, useEffect, forwardRef, useImperativeHandle ,useRef} from 'react';
import { useTranslation } from 'react-i18next';
import ImportData from '@/components/chat-excel/importData'
import ImportProgress from './ImportProgress'
import { useTableData } from '@/hooks/tableHooks';
import { excelFileUploadProgress, getTableMenuList, excelFileUpload, getTableTrash, copyTable, restoreTable, deleteTable } from '@/client/api/smartTable'
import { apiInterceptors,uploadTableExcelFile } from '@/client/api'
import { useRequest } from 'ahooks'
const fileMenuItems = [
  { key: "open", label: "打开" },
  { key: "copy", label: "复制" },
  { key: "delete", label: "删除" },
  { key: "open_copilot", label: "引用到copilot" }
];

const recycleMenuItems = [
  { key: "restore", label: "还原" },
  { key: "deleteForever", label: "彻底删除" }
];

const { Sider } = Layout;
const zeroWidthTriggerDefaultStyle: React.CSSProperties = {
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  width: 16,
  height: 48,
  position: 'absolute',
  top: '50%',
  transform: 'translateY(-50%)',
  border: '1px solid #d6d8da',
  borderRadius: 8,
  right: -8,
};

const CatalogMenus: React.FC<{
  onSelectedItemChange: (selectedItem: string) => void;
  onFileClick: (key: string, file: object) => void;
  collapsed?: boolean;
  setCollapsed?: (collapsed: boolean) => void;
}> = forwardRef(({ onSelectedItemChange, onFileClick,collapsed,setCollapsed },ref) => {
  const { t } = useTranslation();
  const { mode } = useContext(ChatContext);
  const [showFileMenu, setShowFileMenu] = useState(null);
  const [showRecycleMenu, setShowRecycleMenu] = useState(null);
  const [importDataOpen, setimportDataOpen] = useState(false)
  const [importProgressOpen, setImportProgressOpen] = useState(false)
  const [fileListData, setFileListData] = useState([])
  const [recycleBinData, setRecycleBinData] = useState([])
  const [progressData, setProgressData] = useState([])
  
  const handleStartImporting = (data: any) => {
    const { uploadImage } = data
    const formData = new FormData();
    if (data.type == 1) {
      formData.append('excel_file', uploadImage.file.originFileObj)
    }
    apiInterceptors(excelFileUpload({ type: data.type, datasource_id: data.datasource_id, db_name: data.db_name, table_name: data.table_name, table_filter: data.table_filter, file: formData }));
    setimportDataOpen(false)
    setTimeout(()=>{
        getExcelFileUploadProgress()
    },2000)
  }
  const handleCancelImport = () => {
    setimportDataOpen(false)
  }
  let onfileParmas:any = useRef(null);
  const onFileClickChange = ()=>{
    const { key, file } = onfileParmas.current || {};
    if(key){
      onFileClick(key, file);
    }
  }
  const handleFileClick = (key, file) => {
    onfileParmas.current = { key, file };
    if (key === 'delete') {
      TableTrash({ id: file.id })
    } else if (key == 'copy') {
      copyTableData({ id: file.id })
    }else if (key == 'open_copilot'){
      onFileClick(key, file);
    }else if(key==='open'){
       onFileClick(key, file);
    }
  };
  //表格放回收站
  const { run: TableTrash } = useRequest(
    async (data) => {
      return await getTableTrash({ id: data.id })
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { data, success, err_msg } = res.data || {}
        if (success) {
          message.success('删除成功')
          getrecycleBinData(0)
          getTableMenuListData(1)
          onFileClickChange();
        } else {
          message.error(err_msg)
        }
      }
    }
  )
  //表格复制
  const { run: copyTableData } = useRequest(
    async (data) => {
      return await copyTable({ id: data.id })
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { data, success, err_msg } = res.data || {}
        if (success) {
          message.success('复制成功')
          getTableMenuListData(1)
          onFileClickChange();
        } else {
          message.error(err_msg)
        }
      }
    }
  )
  //表格还原
  const { run: restoreTableData } = useRequest(
    async (id) => {
      return await restoreTable({ id })
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { data, success, err_msg } = res.data || {}
        if (success) {
          message.success('操作成功')
          getrecycleBinData(0)
          getTableMenuListData(1)
          onFileClickChange();
        } else {
          message.error(err_msg)
        }
      }
    }
  )
  //表格彻底删除
  const { run: deleteTableForever } = useRequest(
    async (id) => {
      return await deleteTable({ id })
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { data, success, err_msg } = res.data || {}
        if (success) {
          message.success('操作成功')
          getrecycleBinData(0)
          getTableMenuListData(1)
          onFileClickChange();
        } else {
          message.error(err_msg)
        }
      },
      onError: (err: any) => {
        message.error(err.message);
      },
    }
  )
  //回收站操作
  const handleRecycleClick = (key, file) => {
    onfileParmas.current = { key, file };
    if (key === 'restore') {
      restoreTableData(file.id)
    } else if (key === 'deleteForever') {
      deleteTableForever(file.id)
    }
  };

  const triggerStyle: React.CSSProperties = useMemo(() => {
    if (collapsed) {
      return {
        ...zeroWidthTriggerDefaultStyle,
        right: -16,
        borderRadius: '0px 8px 8px 0',
        borderLeft: '1px solid #d5e5f6',
      };
    }
    return {
      ...zeroWidthTriggerDefaultStyle,
      borderLeft: '1px solid #d6d8da',
    };
  }, [collapsed]);

  const selectedBgStyle = useMemo(() => {
    if (mode === 'dark') {
      return {
        backgroundColor: 'rgb(21, 22, 34)',
      };
    }
    return {
      backgroundColor: 'rgba(98, 54, 255, 0.16)',
    };
  }, [mode]);

  const [selectedItem, setSelectedItem] = useState('');
  //selectedItem  recent 最近 favorite 收藏 myDocuments 我的文档 recycleBin 回收站 add 新建 import 导入
  const handleItemClick = (item) => {
    setSelectedItem(item);
    onSelectedItemChange(item);
    if (item === 'import') {
      setimportDataOpen(true)
    } else if (item === 'myDocuments') {
      getTableMenuListData(1)
    } else if (item === 'recycleBin') {
      getrecycleBinData(0)
    }

  };
  const checkProgress = () => {
    setImportProgressOpen(true)
  }
  const cancelCheckProgress = () => {
    setImportProgressOpen(false)
  }
  //表格菜单列表数据
  const { run: getTableMenuListData } = useRequest(
    async (type: number) => {
      let data = {
        'query_type': type
      }
      return await getTableMenuList(data)
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { data, success } = res.data || {}
        if (success) {
          setFileListData(data)
        }
      }
    }
  )
  //表格菜单回收站
  const { run: getrecycleBinData } = useRequest(
    async (type: number) => {
      let data = {
        'query_type': type
      }
      return await getTableMenuList(data)
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { data, success, err_msg } = res.data || {}
        if (success) {
          setRecycleBinData(data)
        } else {
          message.error(err_msg)
        }
      }
    }
  )
  //导入进度
  const { run: getExcelFileUploadProgress } = useRequest(
    async () => {
      return await excelFileUploadProgress()
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { data, success, err_msg } = res.data || {}
        if (success) {
         let filterlist =  data.filter((item)=>item.status===2)
         console.log('filterlist',filterlist)
         if(filterlist.length>0){
             setTimeout(()=>{
            getExcelFileUploadProgress()
        },2000)
         }else{
          getTableMenuListData(1)
          onFileClickChange();
         }
         setProgressData(data)
        
        } else {
          message.error(err_msg)
        }
      }
    }
  )
  //更新进度状态
  const hadleonUpdateProgress = (data) => {
    setProgressData(data)
    getExcelFileUploadProgress()
  }
  useEffect(() => {
    getExcelFileUploadProgress()
    getTableMenuListData(1)
    getrecycleBinData(0)
  }, [])
  const getLeftChange = ()=>{
    getrecycleBinData(0)
    getTableMenuListData(1)
  }
  useImperativeHandle(ref, () => ({
    getLeftChange
  }))
  return (
    <Sider
      className='leftMenu bg-[#fff]  border-r  border-[#d5e5f6] dark:bg-[#ffffff29] dark:border-[#ffffff66]'
      theme={mode}
      width={280}
      collapsible={true}
      collapsed={collapsed}
      onCollapse={setCollapsed}
      collapsedWidth={0}
      trigger={collapsed ? <CaretRightOutlined className='text-base' /> : <CaretLeftOutlined className='text-base' />}
      zeroWidthTriggerStyle={triggerStyle}
    >
      <div className='flex flex-col h-full w-full bg-transparent'>
        <div className='w-full h-50 flex flex-col items-center  jusitify-center py-5 border-b border-borderColor dark:border-darkBorderColor'>
          {/* <Button
            onClick={() => {
              handleItemClick('add');
            }}
            className='w-5/6 py-4 rounded-lg m-auto border-theme-primary text-theme-primary bg-customPurple hover:bg-customPurple2'
            icon={<PlusOutlined />}
          >
            新建
          </Button> */}
          <Button
            onClick={() => {
              handleItemClick('import')
            }}
            className='w-5/6 py-4 rounded-lg m-auto border-theme-primary text-theme-primary bg-customPurple hover:bg-customPurple2'
            icon={<DownloadOutlined />}
          >
            导入
          </Button>
        </div>
        <div className='w-full mt-4 text-base font-semibold text-[#1c2533] dark:text-[rgba(255,255,255,0.85)] mb-4 line-clamp-1'>
        </div>
        <Flex flex={1} vertical={true} className='overflow-y-auto'>
          <div className='mt-2 h-[80vh]' style={{ overflow: 'scroll' }}>
            <div style={{ width: '100%', height: '80vh' }} className='flex flex-col justify-between'>
              <div>
                <div
                  style={{
                    // marginLeft: 10,
                    cursor: 'pointer',
                    padding: '10px 5px 10px 25px',
                    ...(selectedItem === 'recent' ? selectedBgStyle : '')
                  }}
                  onClick={() => handleItemClick('recent')}
                >
                  <span className='mr-1 '><HistoryOutlined style={{ fontSize: '16px' }} /> </span>
                  <span className='font-bold'>最近</span>
                </div>
                <div
                  style={{
                    margin: '0 0 15px 0',
                    cursor: 'pointer',
                    padding: '10px 5px 10px 25px',
                    ...(selectedItem === 'favorite' ? selectedBgStyle : '')
                  }}
                  onClick={() => handleItemClick('favorite')}
                >
                  <span className='mr-1'><StarOutlined style={{ fontSize: '18px' }} /></span>
                  <span className='font-bold'>收藏</span>
                </div>
                <div
                  style={{
                    cursor: 'pointer',
                    padding: '10px 5px 10px 15px',
                    ...(selectedItem === 'myDocuments' ? selectedBgStyle : '')
                  }}
                  onClick={() => handleItemClick('myDocuments')}
                >
                  <span className='mr-1'><UserOutlined style={{ fontSize: '18px' }} /></span>
                  <span className='font-bold'>我的文档</span>
                </div>
                <List
                  style={{ marginLeft: '25px', height: '300px', overflowY: 'auto' }}
                >
                  {fileListData.map((file) => (
                    <List.Item key={file.id} onClick={() => { }} >
                      <List.Item.Meta
                        avatar={<Image src={`/ai/chat_excel_analyze.png`} width={22} height={22} alt='file-icon' preview={false}  />}
                        title={
                          <Tooltip placement="topLeft" title={file.file_name}>
                            <span
                              style={{
                                display: 'inline-block',
                                maxWidth: 200,
                                whiteSpace: 'nowrap',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                verticalAlign: 'middle',
                                cursor: 'pointer',
                              }}
                            >
                              {file.file_name}
                            </span>
                          </Tooltip>
                        }
                      />
                      <Popover
                        content={(
                          <Menu onClick={(e) => handleFileClick(e.key, file)}>
                            {fileMenuItems.map((item) => <Menu.Item key={item.key}>{item.label}</Menu.Item>)}
                          </Menu>
                        )}
                        placement="bottomRight"
                        trigger="click"
                        visible={showFileMenu === file.id}
                        onVisibleChange={(visible) => visible ? setShowFileMenu(file.id) : setShowFileMenu(null)}
                      >
                        <Button type="link" icon={<MoreOutlined />} onClick={() => setShowFileMenu(file.id)} />
                      </Popover>
                    </List.Item>
                  ))}
                </List>
                <div
                  style={{
                    marginBottom: 10,
                    cursor: 'pointer',
                    padding: '10px 5px 10px 15px',
                    ...(selectedItem === 'recycleBin' ? selectedBgStyle : '')
                  }}
                  onClick={() => handleItemClick('recycleBin')}
                >
                  <span className='mr-1'><DeleteOutlined style={{ fontSize: '18px' }} /></span>
                  <span className='font-bold'>回收站</span>
                </div>

                <List
                  style={{ marginLeft: '15px' }}
                >
                  {recycleBinData.map((file) => (
                    <List.Item key={file.id} onClick={() => { }}>
                      <List.Item.Meta
                        avatar={<Image src={`/ai/chat_excel_analyze.png`} width={22} height={22} alt='file-icon' preview={false}  />}
                        title={
                          <Tooltip placement="topLeft" title={file.file_name}>
                            <span
                              style={{
                                display: 'inline-block',
                                maxWidth: 200,
                                whiteSpace: 'nowrap',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                verticalAlign: 'middle',
                                cursor: 'pointer',
                              }}
                            >
                              {file.file_name}
                            </span>
                          </Tooltip>
                        }
                      />
                      <Popover
                        content={(
                          <Menu onClick={(e) => handleRecycleClick(e.key, file)}>
                            {recycleMenuItems.map((item) => <Menu.Item key={item.key}>{item.label}</Menu.Item>)}
                          </Menu>
                        )}
                        placement="bottomRight"
                        trigger="click"
                        visible={showRecycleMenu === file.id}
                        onVisibleChange={(visible) => visible ? setShowRecycleMenu(file.id) : setShowRecycleMenu(null)}
                      >
                        <Button type="link" icon={<MoreOutlined />} onClick={() => setShowRecycleMenu(file.id)} />
                      </Popover>
                    </List.Item>
                  ))}
                </List>
              </div>
              <div style={{ padding: '0 20px 0 10px', borderTop: '1px solid rgba(5, 5, 5, 0.06)' }} className="border-t dark:border-t-[rgba(197,151,2,0.08)]">
                {progressData.length ? (<div>
                  <div className='flex justify-between items-center'>
                    <span>文档传输</span><Button type='link' onClick={() => checkProgress()}>查看进度</Button>
                  </div>
                  <Progress percent={progressData.length === 0 ? 0 : !(progressData.filter(item => item.status === '2').length) ? '100%' : (progressData.filter(item => item.status === '2').length / progressData.length) * 100} showInfo={false} />
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4 }}>
                    <span>{progressData.filter(item => item.status == '1').length}/{progressData.length}</span>
                    <span style={{ fontWeight: 'bold' }}>{progressData.length === 0 ? 0 : !(progressData.filter(item => item.status === '2').length) ? '100%' : (progressData.filter(item => item.status === '2').length / progressData.length) * 100}</span>
                  </div>
                </div>) : <div>
                  <div className='flex justify-between items-center mt-2'>
                    <span className='text-[14px] font-bold'>文档传输</span>
                  </div>
                  <div className='text-[12px] text-[rgb(133, 133, 133)]'>暂未传输任务</div>
                </div>}
              </div>
            </div>
          </div>
        </Flex>
        {importDataOpen && (<ImportData open={importDataOpen} startImporting={handleStartImporting} cancelImport={handleCancelImport} />)}
        {importProgressOpen && (<ImportProgress open={importProgressOpen} cancel={cancelCheckProgress} progressData={progressData} onUpdateProgress={hadleonUpdateProgress} />)}
      </div>
    </Sider>
  );
});

export default CatalogMenus;